package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.query.TravelCondition;
import cn.wolfcode.wolf2w.query.TravelQuery;
import cn.wolfcode.wolf2w.repository.TravelRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.ITravelService;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.AssertUtil;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
* 游记服务接口实现
*/
@Service
//@Transactional  现在写不能事务, 需要讲完复制集才能使用事务
public class TravelServiceImpl implements ITravelService {

    @Autowired
    private TravelRepository repository;

    @Autowired
    private MongoTemplate template;

    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IDestinationService destinationService;

    @Override
    public void save(Travel travel) {
        travel.setId(null);
        repository.save(travel);
    }

    @Override
    public void update(Travel travel) {
        repository.save(travel);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public Travel get(String id) {
        Optional<Travel> op = repository.findById(id);
        // 判断查出来的数据是否为空
        Travel travel = null;
        if (op.isPresent()) {
            travel = op.get();
            travel.setAuthor(userInfoService.get(travel.getUserId()));
            travel.setDest(destinationService.get(travel.getDestId()));
        }
        return travel;
    }

    @Override
    public List<Travel> list() {
        return repository.findAll();
    }

    @Override
    public Page<Travel> query(TravelQuery qo) {
        Query query = new Query();
        // 查询对应游记的状态
        if (qo.getState() != -1) {
            query.addCriteria(Criteria.where("state").is(qo.getState()));
        }
        // 默认排序
        Pageable pageable = PageRequest.of(qo.getCurrentPage()- 1,qo.getPageSize(), Sort.Direction.ASC, "_id");
        Page<Travel> page = DBHelper.query(template, pageable, query, Travel.class);
        // 模型类中的author属性为空，导致前端渲染失败：解决手动添加
        for (Travel travel : page) {
            // 通过游记中的用户id查询用户信息存到author这个属性上
            travel.setAuthor(userInfoService.get(travel.getUserId()));
        }
        return page;
    }

    @Override
    public Page<Travel> queryForApi(TravelQuery qo, UserInfo user) {
        Query query = new Query();

        //根据目的地查询对应目的地的游记
        if (StringUtils.hasLength(qo.getDestId())) {
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }
        // 查询对应游记的状态
        if (qo.getState() != -1) {
            query.addCriteria(Criteria.where("state").is(qo.getState()));
        }
        // 人均消费的查询
        TravelCondition preExpend = TravelCondition.PERSON_EXPEND.get(qo.getPerExpendType());
        if (preExpend != null) {
            query.addCriteria(Criteria.where("perExpend").gte(preExpend.getMin()).lte(preExpend.getMax()));
        }
        // 出行天数的查询
        TravelCondition days = TravelCondition.TRAVEL_DAYS.get(qo.getDayType());
        if (days != null) {
            query.addCriteria(Criteria.where("day").gte(days.getMin()).lte(days.getMax()));
        }
        // 默认排序
        Pageable pageable = PageRequest.of(qo.getCurrentPage()- 1,qo.getPageSize(), Sort.Direction.ASC, "_id");
        //最新与最热的排序操作
        if (qo.getOrderType() == 1){
            // 最新的排序(按照发布时间排)
            pageable = PageRequest.of(qo.getCurrentPage()- 1,qo.getPageSize(), Sort.Direction.DESC, "releaseTime");
        }else if (qo.getOrderType() == 2){
            // 最热的排序(按照阅读数排)
            pageable = PageRequest.of(qo.getCurrentPage()- 1,qo.getPageSize(), Sort.Direction.DESC, "viewnum");
        }

        if (user != null){
            Criteria criteriaOr = new Criteria();
            Criteria criteriaAnd = new Criteria();
            criteriaAnd.andOperator(Criteria.where("state").is(Travel.STATE_RELEASE), Criteria.where("isPublic").is(Travel.ISPUBLIC_YES));
            query.addCriteria(criteriaOr.orOperator(Criteria.where("userId").is(user.getId()), criteriaAnd));
        }else {
            // 判断是否已发布的（审核通过的）与公开的
            query.addCriteria(Criteria.where("state").is(Travel.STATE_RELEASE).and("isPublic").is(Travel.ISPUBLIC_YES));
        }
        Page<Travel> page = DBHelper.query(template, pageable, query, Travel.class);
        // 模型类中的author属性为空，导致前端渲染失败：解决手动添加
        for (Travel travel : page) {
            // 通过游记中的用户id查询用户信息存到author这个属性上
            travel.setAuthor(userInfoService.get(travel.getUserId()));
        }
        return page;
    }

    @Override
    public void saveOrUpdate(Travel travel, UserInfo user) {
        // 根据目的地id查询名称插入destName中
        Destination destination = destinationService.get(travel.getDestId());
        travel.setDestName(destination.getName());
        // 生成最后更新的时间
        travel.setLastUpdateTime(new Date());
        // 设置发布时间为null
        travel.setReleaseTime(null);
        if(StringUtils.hasLength(travel.getId())){
            Travel oldTravel = this.get(travel.getId());
            // 判断当前数据是否是当前用户的，不是就不能修改
            if (user != null) {
                AssertUtil.isEquals(oldTravel.getUserId(), user.getId(), "这条数据不是你的，别乱来");
            }
            travel.setCreateTime(oldTravel.getCreateTime());
            travel.setUserId(oldTravel.getUserId());
            //update
            this.update(travel);
        }else{
            //save
            // 保存时设置用户id当前用户进去
            travel.setUserId(user.getId());
            // 创建的时间
            travel.setCreateTime(new Date());
            this.save(travel);
        }
    }

    @Override
    public void updateState(String id, int state) {
        AssertUtil.hasLength(id, "参数异常");
        //1.判断是否满足审核条件
        Travel travel = this.get(id);
        if (travel == null) {
            throw new LogicException("参数异常");
        }
        // 判断当前游记的状态是否为待审核状态才进行审核
        if (travel.getState() != Travel.STATE_WAITING) {
            throw new LogicException("当前数据已审核");
        }
        // 进行审核操作
        if (state == Travel.STATE_RELEASE){
            //审核通过之后要做什么
            // 1.state设置为审核通过
            travel.setState(state);
            // 2.发布时间设置为当前时间
            travel.setReleaseTime(new Date());
            // 3.最后修改时间为当前时间
            travel.setLastUpdateTime(new Date());
            //之后的可以加上审计人的信息与原因
        }else if (state == Travel.STATE_REJECT){
            //审核拒绝之后要做什么
            // 1.state设置为拒绝
            travel.setState(Travel.STATE_REJECT);
            // 2.发布时间设置为null
            travel.setReleaseTime(null);
            // 3.最后修改时间为当前时间
            travel.setLastUpdateTime(new Date());
            //之后的可以加上审计人的信息与原因
        }else {
            //其他情况都是失败的
            throw new LogicException("参数异常");
        }
        // 最后更新数据
        this.update(travel);
    }

    @Override
    public List<Travel> queryTravelTop3(String destId) {
        Pageable pageable = PageRequest.of(0, 3, Sort.Direction.DESC, "viewnum");
        return repository.findByDestId(destId, pageable);
    }

    @Override
    public List<Travel> findByDestId(String destId) {
        List<Travel> travels = repository.findByDestId(destId, null);
        for (Travel travel : travels) {
            travel.setAuthor(userInfoService.get(travel.getUserId()));
        }
        return travels;
    }
}
